// 通用工具函数

// 防抖函数
export const debounce = (func, wait, immediate = false) => {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      timeout = null
      if (!immediate) func(...args)
    }
    const callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    if (callNow) func(...args)
  }
}

// 节流函数
export const throttle = (func, limit) => {
  let inThrottle
  return function() {
    const args = arguments
    const context = this
    if (!inThrottle) {
      func.apply(context, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

// 深拷贝
export const deepClone = (obj) => {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj.getTime())
  if (obj instanceof Array) return obj.map(item => deepClone(item))
  if (typeof obj === 'object') {
    const clonedObj = {}
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key])
      }
    }
    return clonedObj
  }
}

// 生成唯一ID
export const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

// 获取当前页面参数
export const getPageParams = () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  return currentPage.options || {}
}

// 获取系统信息
export const getSystemInfo = () => {
  return new Promise((resolve, reject) => {
    // #ifdef MP-WEIXIN
    // 微信小程序使用新的API
    Promise.all([
      uni.getWindowInfo(),
      uni.getDeviceInfo(),
      uni.getAppBaseInfo(),
      uni.getSystemSetting()
    ]).then(([windowInfo, deviceInfo, appBaseInfo, systemSetting]) => {
      // 合并系统信息
      const systemInfo = {
        ...windowInfo,
        ...deviceInfo,
        ...appBaseInfo,
        ...systemSetting
      }
      resolve(systemInfo)
    }).catch((error) => {
      console.error('获取系统信息失败:', error)
      // 降级处理：使用旧的API
      uni.getSystemInfo({
        success: resolve,
        fail: reject
      })
    })
    // #endif
    
    // #ifndef MP-WEIXIN
    // 其他平台使用通用API
    uni.getSystemInfo({
      success: resolve,
      fail: reject
    })
    // #endif
  })
}

// 获取网络状态
export const getNetworkType = () => {
  return new Promise((resolve, reject) => {
    uni.getNetworkType({
      success: resolve,
      fail: reject
    })
  })
}

// 复制到剪贴板
export const copyToClipboard = (text) => {
  return new Promise((resolve, reject) => {
    uni.setClipboardData({
      data: text,
      success: resolve,
      fail: reject
    })
  })
}

// 选择图片
export const chooseImage = (count = 1, sizeType = ['original', 'compressed']) => {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count,
      sizeType,
      success: resolve,
      fail: reject
    })
  })
}

// 预览图片
export const previewImage = (urls, current = 0) => {
  return new Promise((resolve, reject) => {
    uni.previewImage({
      urls,
      current,
      success: resolve,
      fail: reject
    })
  })
}

// 拨打电话
export const makePhoneCall = (phoneNumber) => {
  return new Promise((resolve, reject) => {
    uni.makePhoneCall({
      phoneNumber,
      success: resolve,
      fail: reject
    })
  })
}

// 获取位置信息
export const getLocation = (type = 'gcj02') => {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type,
      success: resolve,
      fail: reject
    })
  })
}

// 数组去重
export const uniqueArray = (arr, key) => {
  if (key) {
    const seen = new Set()
    return arr.filter(item => {
      const value = item[key]
      if (seen.has(value)) {
        return false
      }
      seen.add(value)
      return true
    })
  }
  return [...new Set(arr)]
}

// 数组分组
export const groupBy = (arr, key) => {
  return arr.reduce((groups, item) => {
    const group = item[key]
    groups[group] = groups[group] || []
    groups[group].push(item)
    return groups
  }, {})
}

// 数组排序
export const sortBy = (arr, key, order = 'asc') => {
  return arr.sort((a, b) => {
    const aVal = a[key]
    const bVal = b[key]
    if (order === 'asc') {
      return aVal > bVal ? 1 : -1
    } else {
      return aVal < bVal ? 1 : -1
    }
  })
}

// 随机数
export const random = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1)) + min
}

// 随机字符串
export const randomString = (length = 8) => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

// 延迟函数
export const delay = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms))
}

// 环境检测
export const isWechat = () => {
  // #ifdef MP-WEIXIN
  return true
  // #endif
  return false
}

export const isMiniProgram = () => {
  // #ifdef MP
  return true
  // #endif
  return false
}

export const isApp = () => {
  // #ifdef APP-PLUS
  return true
  // #endif
  return false
} 